/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Class;

import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author iscpochi
 */
public class Conexion {
    public static Connection con;
    public static Statement stmt;
    public static ResultSet rs;
    static String connectionString;
    
    public Conexion(String connectionString, String dbUser, String dbPass){
        try{
            Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,"No se pudo cargar el puente JDBC-ODBC.");
        }
        
        try{
            con = DriverManager.getConnection(connectionString,dbUser,dbPass);
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,e.getMessage() );
        }
    }
    
    public Conexion(String dato){
        try {
            Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
        } catch( Exception e ) {
            System.out.println( "No se pudo cargar el puente JDBC-ODBC." );
            return;
        }
        try{
            con=DriverManager.getConnection("jdbc:odbc:mydsn","","");
            stmt=con.createStatement();
            try{
              rs=stmt.executeQuery("Select Producto,Precio from Productos where Producto='"+dato+"'");
            }catch(SQLException s){
              JOptionPane.showMessageDialog(null, s);
            }
        }catch(SQLException s){
            JOptionPane.showMessageDialog(null, s);
        }
    }
    
    public DefaultTableModel executeQuery(String query){
        DefaultTableModel model = new DefaultTableModel();
        try{
            Statement stat = con.createStatement();
            ResultSet rs = stat.executeQuery(query);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int cols = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[cols];
            for (int i = 0; i < cols; i++){
               etiquetas[i] = metaDatos.getColumnLabel(i + 1);
            }
            model.setColumnIdentifiers(etiquetas);
            while (rs.next())
            {
               Object [] fila = new Object[cols];
               for (int i=0;i<cols;i++)
                  fila[i] = rs.getObject(i+1); // El primer indice en rs es el 1, no el cero, por eso se suma 1.
               model.addRow(fila);
            }
        }catch(SQLException ex){
            System.out.println("search: " + ex.getMessage());
        }
        return model;
    }
  
  
    public Connection getConnection(){
        return con;
    }
  
    public void cerrar(){
        try{
            con.close();
        }catch(SQLException ex){}
    }
}
